﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

using Microsoft.Extensions.DependencyInjection;

using Newtonsoft.Json;

using Utils;
using Utils.Cache;

namespace System
{
    /// <summary>
    /// 缓存填充器，从缓存件中读取名称并填充
    /// </summary>
    public class AutoCachePaddingConverter : JsonConverter
    {
        private readonly string cacheKey;

        public AutoCachePaddingConverter(string cacheKey)
        {
            if (cacheKey.IsNullOrEmpty())
                throw new ArgumentNullException(nameof(cacheKey));
            this.cacheKey = "auto_cache_" + cacheKey;
        }
        public override bool CanConvert(Type objectType)
        {
            return true;
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            return serializer.Deserialize(reader, objectType) ?? existingValue;
        }

        public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
        {

            serializer.Serialize(writer, value);
            if (value != null && AutoCacheQueryable.IsLoad())
            {
                var propertyName = writer.Path.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries).Last();
                try
                {
                    var cacheValue = AutoCacheQueryable.GetObject(cacheKey, value.ToString());
                    if (cacheValue != null)
                    {
                        if (propertyName.EndsWith("Id"))
                        {
                            propertyName = propertyName.Substring(0, propertyName.Length - 2);
                        }
                        foreach (var item in cacheValue)
                        {
                            var name = item.Key.Substring(0, 1).ToUpper() + item.Key.Substring(1);
                            writer.WritePropertyName(propertyName + name);
                            serializer.Serialize(writer, item.Value);
                        }
                    }
                }
                catch (Exception)
                {
                    Console.WriteLine("自动缓存异常了：" + cacheKey);
                }

            }
        }
    }
}
